﻿
using System.Linq;
using FacebookXmpp.Parse;

namespace FacebookXmpp.Stanzas
{
	internal class Presence : Stanza
	{
		public Presence(string status)
		{
			ResponseExpectation = Expectation.Low;

            if (!string.IsNullOrEmpty(status))
                NextResponse = string.Format("<presence><status>{0}</status><show></show><priority>1</priority></presence>", status);
        }

		internal override StanzaListenCriteria ListenFor
		{
			get { return new StanzaListenCriteria( "presence" ); }
		}

        public override void ProcessResponse(MessageData recieved)
		{
            string fromId = recieved.Attributes["from"];
            if (!Stream.Dashboard.Online.Contains(fromId))
                Stream.Dashboard.Online.Add(fromId);
            Person friend = Stream.Dashboard.Friends.FirstOrDefault(p => p.Id == fromId);
            if (friend != null)
            {
                friend.State = Status.Available;
                MessageData show = recieved.Path("show") as MessageData;
                if (show != null)
                {
                    if (show.Value.ToString() == "away")
                        friend.State = Status.Away;   
                }
            }
		}
	}
}